/**
 * 调岗列表页面
 */
import React from 'react';
import { Table, Form, Input, Tooltip, Divider } from 'antd';
import { withRouter, router, Link } from 'umi';
import { connect } from 'umi';
import moment from 'moment';

import { queryStringToAry, queryAryToString } from '@/utils/utils';
import useDictionary from '@/hooks/useDictionary';
import { Icon } from '@/pages/Recruitment/components';
import { getTransferList } from '@/pages/OnboardAndLeave/TransferPost/services';

import { DividerContainer } from '@/molecules';
import { Pagination, CollapseSearch } from '@/components';
import { useRequest, defaultFormatResult, useWorkFlow } from '@/hooks';

import { TRANSFER_TYPE, TRANSFER_STATUS } from './dictionary';

const formatOrg = orgName => {
    const nameArr = orgName?.split('/') || [];
    if (nameArr.length === 0) {
        return orgName;
    }
    nameArr.splice(0, nameArr.length - 1, '');
    return nameArr;
};

const renderCompare = ({ label, origin, next, originFull, nextFull }) => (
    <div>
        <div style={{ height: 21 }}>
            <Tooltip title={`原${label}: ${originFull || origin}`}>{origin}</Tooltip>
        </div>
        <div style={{ position: 'relative', padding: '16px 0' }}>
            <div
                style={{
                    background: '#e8e8e8',
                    height: 1,
                    position: 'absolute',
                    left: -16,
                    width: 'calc(100% + 32px)'
                }}
            ></div>
        </div>
        <div style={{ height: 21 }}>
            <Tooltip title={`新${label}: ${nextFull || next}`}>{formatOrg(next)}</Tooltip>
        </div>
    </div>
);

const renderCompareLabel = label => (
    <div>
        {label}
        <Tooltip
            title={
                <>
                    <div>原{label}</div>
                    <Divider
                        style={{
                            margin: '4px 0',
                            opacity: 0.32
                        }}
                    />
                    <div>新{label}</div>
                </>
            }
        >
            <i
                className="icon iconfont iconTips"
                style={{
                    marginLeft: 4,
                    cursor: 'pointer',
                    fontSize: '24px',
                    verticalAlign: '-0.125em',
                    color: 'rgba(0, 0, 0, 0.4)'
                }}
            ></i>
        </Tooltip>
    </div>
);

const getOrderState = (query, field) => {
    if (!query?.orderByField) {
        return undefined;
    }
    const arr = query.orderByField.split('|');
    if (arr[0] === field) {
        return arr[1];
    }
    return undefined;
};

const replaceOrder = str => (str ? str.replace('|descend', '|desc').replace('|ascend', '|asc') : undefined);

const Process = ({ form, location, appendQuery = {} }) => {
    const { query = {} } = location;

    const [doingStatus, ...historyStatus] = TRANSFER_STATUS;
    const filterStatus = appendQuery.searchType === 1 ? [doingStatus] : historyStatus;

    const formatQuery = {
        ...query,
        sex: queryStringToAry(query.sex),
        transferPositionStatus: queryStringToAry(query.transferPositionStatus),
        applyTime: getOrderState(query, 'applyTime')
    };

    const [sexTypeList, getSexTypeText] = useDictionary('sexType');

    const { data = { rows: [], total: 0 }, loading, run } = useRequest(getTransferList, {
        manual: true,
        ...defaultFormatResult
    });

    const { view } = useWorkFlow({ launchParam: { type: 'TransferPositionApply' } });

    React.useEffect(() => {
        const { sex, transferPositionStatus, ...rest } = query;
        run({
            ...rest,
            ...appendQuery,
            sexList: queryStringToAry(query.sex),
            transferPositionStatusList: queryStringToAry(query.transferPositionStatus),
            orderByField: replaceOrder(query.orderByField)
        });
    }, [query, appendQuery]);

    const setQuery = params => {
        history.push({ query: { ...query, ...params } });
    };

    const operationColumns = [
        {
            title: '操作',
            dataIndex: 'id',
            width: 140,
            onCell: () => ({
                onClick: e => {
                    e.stopPropagation();
                }
            }),
            render: (text, record) => (
                <DividerContainer>
                    <Icon
                        title={appendQuery.searchType === 1 ? '审批' : '查看审批详情'}
                        type={appendQuery.searchType === 1 ? 'Approval_O' : 'chakanxiangqing'}
                        onClick={() => {
                            const { processInstanceId } = record;
                            view({ processInstanceId });
                        }}
                    />
                </DividerContainer>
            )
        }
    ];

    const columns = [
        {
            title: '姓名',
            dataIndex: 'employeeName',
            render: (text, record) => (
                <Link
                    to={{
                        pathname: '/office/personnelManagement/organization/employeeList/detail',
                        query: { employeeCode: record.employeeCode }
                    }}
                >
                    {text}
                </Link>
            )
        },
        {
            title: '性别',
            dataIndex: 'sex',
            filteredValue: formatQuery.sex,
            filters: sexTypeList,
            render: text => getSexTypeText(text)
        },
        {
            title: renderCompareLabel('组织机构'),
            dataIndex: 'organizationName',
            render: (text, record) =>
                record.fullOrganizationName === record.transferToFullOrganizationName ? (
                    <Tooltip title={`新/原组织机构: ${record.fullOrganizationName || record.organizationName}`}>
                        {text}
                    </Tooltip>
                ) : (
                    renderCompare({
                        label: '组织机构',
                        origin: record.organizationName,
                        next: record.transferToOrganizationName,
                        originFull: record.fullOrganizationName,
                        nextFull: record.transferToFullOrganizationName
                    })
                )
        },
        {
            title: renderCompareLabel('岗位'),
            dataIndex: 'dutyName',
            render: (text, record) =>
                renderCompare({
                    label: '岗位',
                    origin: record.dutyName,
                    next: record.transferToDutyName
                })
        },
        {
            title: '行政机构',
            dataIndex: 'companyName'
        },
        {
            title: '调岗类型',
            dataIndex: 'transferPositionType',
            // filters: TRANSFER_TYPE,
            render: text => TRANSFER_TYPE.find(item => item.value === text)?.text
        },
        {
            title: '发起日期',
            dataIndex: 'applyTime',
            sortOrder: formatQuery.applyTime,
            sorter: true,
            render: text => moment(text).format('YYYY-MM-DD')
        },
        {
            title: '状态',
            dataIndex: 'transferPositionStatus',
            filteredValue: formatQuery.transferPositionStatus,
            filters: filterStatus,
            render: (text, record) => (
                <span style={{ color: record.transferPositionStatus === 4 ? '#F5222D' : 'rgba(0, 0, 0, 0.65)' }}>
                    {TRANSFER_STATUS.find(item => item.value === text)?.text}
                </span>
            )
        },
        ...operationColumns
    ];

    const handlePaginationChange = pagination => {
        const { current, pageSize } = pagination;
        setQuery({ pageNo: current, pageSize });
    };

    const handleTableChange = (_, filters = {}, sorter) => {
        const { sex, transferPositionStatus } = filters;
        const { field, order } = sorter;
        setQuery({
            sex: queryAryToString(sex),
            transferPositionStatus: queryAryToString(transferPositionStatus),
            orderByField: order ? `${field}|${order}` : undefined,
            pageNo: 1
        });
    };

    const handleSubmit = () => {
        form.validateFields((err, values) => {
            if (!err) {
                setQuery({
                    ...values,
                    pageNo: 1
                });
            }
        });
    };

    return (
        <>
            <CollapseSearch onSubmit={handleSubmit} showExpand={false}>
                <Form.Item label="">
                    {form.getFieldDecorator('name', {
                        initialValue: formatQuery.keyword
                    })(<Input style={{ width: 252 }} placeholder="搜索姓名、机构、岗位" allowClear maxLength={200} />)}
                </Form.Item>
            </CollapseSearch>
            <Table
                rowKey={row => row.id}
                columns={columns}
                dataSource={data.rows}
                pagination={false}
                scroll={{ x: 'max-content' }}
                onChange={handleTableChange}
                loading={loading}
            />
            <Pagination
                current={formatQuery.pageNo}
                pageSize={formatQuery.pageSize}
                loading={loading}
                total={data.total}
                onChange={handlePaginationChange}
            />
        </>
    );
};

export default withRouter(connect(({ user }) => ({ user: user.currentUser }))(Form.create()(Process)));
